package com.simen.downloader;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import com.simen.downloader.listener.DownloadListener;


/**
 * Created by zhangming on 16/4/11.
 */
public class DownloadService extends Service {

    public enum TYPE {
        clear, pause, resume;
    }

    private volatile MessageHandler handler;
    private DownloadCache downloadCache;
    private DownloadEngine engine;

    public DownloadService() {
        Downloader downloader = Downloader.getInstance();
        this.downloadCache = downloader.getConfiguration().downloadCache;
        this.engine = downloader.getEngine();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // TODO: 16/5/13 清理工作

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String key = intent.getStringExtra("fileUrl");
            TYPE type = (TYPE) intent.getSerializableExtra("type");
            if (type != null && !TextUtils.isEmpty(key)) {
                handleWork(key, type);
            }else{
                //打印实际线程状态

            }
        }
        return START_NOT_STICKY;
    }

    private void handleWork(String key, TYPE type) {
        switch (type) {
            case pause:

                break;
            case clear:

                break;
            case resume:
                DownloadInfor downloadInfor = Downloader.getInstance()
                        .getDownloadInfor(key);
                if (downloadInfor != null) {
                    if (!downloadInfor.isCollected()) {
                        downloadInfor.loader.get().onResume(key);
                    }
                    submit(new DownloadThread(engine, downloadInfor, getHandler()));
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        Downloader.getInstance().pauseAll();
        engine.stop();  // FIXME: 16/5/13 彻底结束线程
        super.onDestroy();
    }

    void submit(Runnable runnable) {
        engine.submit(runnable);
    }

    private Handler getHandler() {
        if (handler == null) {
            handler = new MessageHandler(downloadCache);
        }
        return handler;
    }

    private static class MessageHandler extends Handler {

        private final DownloadCache downloadCache;

        public MessageHandler(DownloadCache downloadCache) {
            this.downloadCache = downloadCache;
        }

        @Override
        public void dispatchMessage(Message msg) {
            if (msg.obj != null) {
                //进度消息
                DownloadStatus status = (DownloadStatus) msg.obj;
                downloadCache.setStatus(status.storageFile);
                if (status.listener != null) {
                    status.listener.onProgress(status.storageFile.getFileUrl(), status.storageFile.getProgress());
                }
                return;
            }
            Runnable messageRunnable = msg.getCallback();
            if (messageRunnable instanceof MessageRunnable) {
                DownloadStatus status = ((MessageRunnable) messageRunnable).downloadStatus;
                downloadCache.setStatus(status.storageFile);
                messageRunnable.run();
            } else if (messageRunnable != null) {
                messageRunnable.run();
            }
        }
    }

    static abstract class MessageRunnable implements Runnable {
        final DownloadStatus downloadStatus;

        public MessageRunnable(DownloadStatus downloadStatus) {
            this.downloadStatus = downloadStatus;
        }
    }

    static class DownloadStatus {
        final DownloadListener listener, baselistener;
        final ParcelFile storageFile;

        public DownloadStatus(ParcelFile storageFile, DownloadListener listener) {
            this.listener = listener;
            this.storageFile = storageFile;
            this.baselistener = null;
        }

        public DownloadStatus(ParcelFile storageFile, DownloadListener listener, DownloadListener baselistener) {
            this.listener = listener;
            this.storageFile = storageFile;
            this.baselistener = baselistener;
        }

    }


}
